﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aribaccio;
using Aribaccio.Security;
using BDPAutodetect.DataService;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;

namespace BDPAutodetect.Mgrcore
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public partial class UserManager : BaseManager
    {
        /// <summary>
        /// 基础数据操作实例
        /// </summary>
        protected IDataServiceBasic DataService { get; set; }
        /// <summary>
        /// 角色权限管理实例
        /// </summary>
        protected RolePowerManager RolePowerMgr { get; set; }
        /// <summary>
        /// 记录登录信息
        /// </summary>
        protected MLoginDto? LoginInfo { get; set; }
        /// <summary>
        /// 登录用户信息
        /// </summary>
        [ObservableProperty]
        protected MUserDto? loginUser;
        /// <summary>
        /// 用户信息集合
        /// </summary>
        public List<MUserDto> Users { get; protected set; }

        /// <summary>
        /// 构造函数[注入]
        /// </summary>
        public UserManager(IDataServiceBasic argDataService, RolePowerManager arRrolePowerManager, ISecurity argSecurity)
            : base("用户管理中心")
        {
            this.DataService = argDataService;
            this.RolePowerMgr = arRrolePowerManager;
            this.Users = new List<MUserDto>();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public override async Task Initialize()
        {
            //获取数据库数据
            var results = this.DataService.SelectModelItemsTask<TBasicUser>();
            await results.ConfigureAwait(false);

            if (results == null
              || results.Result == null || !results.Result.ResultState
              || results.Result.Data == null || results.Result.Data.Count <= 0) return;

            foreach (var item in results.Result.Data)
            {
                if (item == null) continue;
                this.Users.Add(new MUserDto(item.ID, item.Name)
                {
                    NameNick = item.NameNick,
                    Password = item.Password,
                    PasswordDisplay = this.DataService.Decrypt(item.Password),
                    Freezed = item.Freezed,
                    Logined = item.Logined,
                    Role = this.RolePowerMgr.GetRole(item.RoleID)
                });
            }

            //设置当前登录用户信息
            if (this.Users.Count <= 0 || LoginInfo == null) return;
            this.LoginUser = this.Users.FirstOrDefault(v => v.Name == LoginInfo.UserName);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="argLoginDto">用户传输模型对象</param>
        /// <returns></returns>
        public async Task<Result> UserLogin(MLoginDto argLoginDto)
        {
            return await Task.Run(() =>
            {
                Result result = new Result(ResultStatus.Failure);
                try
                {
                    ResultModel<TBasicUser> resultLogin = this.DataService.UserLogin<TBasicUser>(argLoginDto);
                    if (!resultLogin.ResultState || resultLogin.Data == null)
                    {
                        result.ResultMsg = $"登录失败, {resultLogin.ResultMsg}";
                        return result;
                    }
                    result.ResultCode = ResultStatus.Succeed;
                    //存储登录信息
                    this.LoginInfo = argLoginDto;
                }
                catch (Exception)
                {
                    result.ResultCode = ResultStatus.Exception;
                }
                return result;
            });
        }

        /// <summary>
        /// 新增用户数据
        /// </summary>
        /// <returns></returns>
        public async Task<MUserDto?> InsertUser(MUserDto argUserDto)
        {
            if (argUserDto == null) return null;
            argUserDto.Password = this.DataService.Encrypt(argUserDto.PasswordDisplay);
            TBasicUser user = argUserDto.CloneTData();
            if (this.CheckExsits(user)) return null;

            var result = this.DataService.InsertTask(user);
            await result.ConfigureAwait(false);
            if (result == null || result.Result == null || !result.Result.ResultState) return null;

            var resultData = this.DataService.SelectModelItemTask<TBasicUser>(v => v.Name == user.Name);
            await resultData.ConfigureAwait(false);
            if (resultData == null || resultData.Result == null || !resultData.Result.ResultState || resultData.Result.Data == null) return null;

            MUserDto userData = new MUserDto(resultData.Result.Data.ID, resultData.Result.Data.Name)
            {
                NameNick = argUserDto.NameNick,
                Password = argUserDto.Password,
                PasswordDisplay = argUserDto.PasswordDisplay,
                Freezed = argUserDto.Freezed,
                Logined = argUserDto.Logined,
                Role = argUserDto.Role,
            };
            this.Users.Add(userData);
            return userData;
        }

        /// <summary>
        /// 删除用户数据
        /// </summary>
        /// <returns></returns>
        public async Task<bool> DeleteUser(MUserDto argUserDto)
        {
            if (argUserDto == null) return false;
            Task<Result> result = this.DataService.DeleteWhereTask<TBasicUser>(v => v.ID == argUserDto.ID);
            await result.ConfigureAwait(false);
            if (result != null && result.Result.ResultState)
            {
                //移除缓存
                var currUser = this.Users.First(v => v.ID == argUserDto.ID);
                this.Users.Remove(currUser);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 更新用户数据
        /// </summary>
        /// <param name="argUserDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateUser(MUserDto argUserDto)
        {
            if (argUserDto == null) return false;
            argUserDto.Password = this.DataService.Encrypt(argUserDto.PasswordDisplay);
            TBasicUser user = argUserDto.CloneTData();
            if (this.CheckExsits(user)) return false;

            var result = this.DataService.UpdateWhereTask<TBasicUser>(user, v => v.ID == user.ID);
            await result.ConfigureAwait(false);
            if (result != null && result.Result != null && result.Result.ResultState)
            {
                var userData = this.Users.First(v => v.ID == argUserDto.ID);
                userData.Name = argUserDto.Name;
                userData.NameNick = argUserDto.NameNick;
                userData.Role = argUserDto.Role;
                userData.Password = argUserDto.Password;
                userData.PasswordDisplay = argUserDto.PasswordDisplay;
                userData.Freezed = argUserDto.Freezed;
                userData.Logined = argUserDto.Logined;
                return true;
            }
            return false;
        }


        /// <summary>
        /// 检测从机设备名称是否存在
        /// </summary>
        /// <param name="argUserDto"></param>
        /// <returns></returns>
        public bool CheckExsits(TBasicUser argUserDto)
        {
            Result check = argUserDto.ID > 0
                ? this.DataService.Exsits<TBasicUser>(v => v.ID != argUserDto.ID && v.Name.Equals(argUserDto.Name, StringComparison.OrdinalIgnoreCase))
                : this.DataService.Exsits<TBasicUser>(v => v.Name.Equals(argUserDto.Name, StringComparison.OrdinalIgnoreCase));
            return (check != null && check.ResultState);
        }

        /// <summary>
        /// 获取角色集合
        /// </summary>
        public List<MRoleDto> GetRoles(bool IsSupered = false)
        {
            return this.RolePowerMgr.GetRoles(IsSupered);
        }

        /// <summary>
        /// 获取用户集合
        /// </summary>
        /// <param name="IsSupered"></param>
        /// <returns></returns>
        public List<MUserDto> GetUsers(bool IsSupered = false)
        {
            if (IsSupered) return this.Users;
            var users = this.Users.Where(v => v.Supered == 0);
            return users != null ? users.ToList() : new List<MUserDto>();
        }

        /// <summary>
        /// 获取用户权限列表
        /// </summary>
        /// <param name="argParentID">父级权限ID，默认0表示顶层</param>
        /// <returns></returns>
        public async Task<List<MPowerPermission>> GetUserPowers(int argParentID)
        {
            return await Task.Run(() =>
            {
                int nRoleID = this.LoginUser?.Role?.ID ?? 0;
                var powers = this.RolePowerMgr.GetPowers(nRoleID, argParentID);
                return powers != null ? powers : new List<MPowerPermission>();
            });
        }
    }
}
